import java.util.PriorityQueue;

public class Solution1 {
     // 解法一：优先级队列
    public ListNode mergeKLists(ListNode[] lists) {
        // 1. 创建一个小根堆
        PriorityQueue<ListNode> heap = new PriorityQueue<>((v1, v2) -> v1.val - v2.val);

        // 2. 把所有的头结点放进小根堆中
        for(ListNode head : lists) {
            if(head != null) {
                heap.offer(head);
            }
        }

        // 3. 合并链表
        ListNode ret = new ListNode();
        ListNode prev = ret;
        while(!heap.isEmpty()) {
            ListNode t = heap.poll();
            prev.next = t;
            prev = prev.next;
            if(t.next != null) {
                heap.offer(t.next);
            }
        }
        return ret.next;
    }

    // 解法二：分治法 - 递归
    public ListNode mergeKLists2(ListNode[] lists) {
        return merge(lists, 0, lists.length - 1);
    }

    public ListNode merge(ListNode[] lists, int left, int right) {
        if(left > right) {
            return null;
        }else if(left == right) {
            return lists[left];
        }

        // 1. 平分数组
        int mid  = (left + right) / 2;
        // [left, mid] [mid + 1, right]

        // 2. 递归处理左右两个部分
        ListNode l1 = merge(lists, left, mid);
        ListNode l2 = merge(lists, mid + 1, right);

        // 3. 合并两个有序链表
        return mergeTwoList(l1, l2);
    }

    public ListNode mergeTwoList(ListNode l1, ListNode l2) {
        // 处理边界情况
        if(l1 == null) {
            return l2;
        }
        if(l2 == null) {
            return l1;
        }

        ListNode cur1 = l1;
        ListNode cur2 = l2;
        ListNode ret = new ListNode();
        ListNode prev = ret;
        while(cur1 != null && cur2 != null) {
            if(cur1.val <= cur2.val) {
                prev.next = cur1;
                cur1 = cur1.next;
                prev = prev.next;
            }else {
                prev.next = cur2;
                cur2 = cur2.next;
                prev = prev.next;
            }
        }

        while(cur1 != null) {
            prev.next = cur1;
            cur1 = cur1.next;
            prev = prev.next;
        }

        while(cur2 != null) {
            prev.next = cur2;
            cur2 = cur2.next;
            prev = prev.next;
        }

        return ret.next;
    }
}
